package com.sanqing.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sanqing.dao.base.BaseDao;
import com.sanqing.po.Income;
import com.sanqing.po.User;
import com.sanqing.service.IncomeService;
import com.sanqing.util.Page;
import com.sanqing.util.PageResult;
import com.sanqing.util.PageUtil;
import com.sanqing.util.TimeHelper;

@Service("incomeService")
@Transactional(readOnly = true)
public class IncomeServiceImpl implements IncomeService {

	@Resource(name = "incomeDao")
	private BaseDao<Income, String> incomeDao;

	@Override
	public PageResult queryIncomeByPage(Page page, Income income, User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		String hql = "from Income a where 1=1";
		if("1".equals(user.getUserType())){
			hql = hql+" and a.agent is null";
		}
//		if("2".equals(user.getUserType())){
//			hql = hql+" and a.agent."
//		}
		page = PageUtil.createPage(page.getEveryPage(), (int) incomeDao.countHqlResult(hql, map), page.getCurrentPage());// 根据总记录数创建分页信息
		List<Income> list = incomeDao.findByPage(page, hql, map);// 通过分页信息取得试题
		PageResult result = new PageResult(page, list);// 封装分页信息和记录信息，返回给调用处
		return result;
	}

	@Override
	@Transactional(readOnly = false)
	public void add(Income income) {
		income.setCreateTime(TimeHelper.getCurrentTime());
		incomeDao.save(income);
	}

	@Override
	public Income getById(String id) {
		return incomeDao.getByKey(id);
	}

	@Override
	@Transactional(readOnly = false)
	public void edit(Income income) {
		Income r = incomeDao.getByKey(income.getId());
		BeanUtils.copyProperties(income, r, new String[] {"createTime"});
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(String id) {
		incomeDao.delete(id);
	}

}
